import { loginUserApi, order_querycartApi, infoUserApi } from '@/api/user'
import {
  removeAllSavedValue, getCategoryTypeList, isPhone
  , saveToken, getToken, saveUserName, hasTokens
  , getroleID, saveroleID, removeroleID
  , superAdminRoutes, bigAgentRoutes, mainDealerRoutes, smallDealerRoutes
  , MsuperAdminRoutes, MbigAgentRoutes, MmainDealerRoutes, MsmallDealerRoutes
} from '@/utils/auth'
import { adminV, agencyV, dealerMV, dealerV } from '@/control'
import { resetRouter } from '@/router'

import { constantRoutes } from '@/router'
// import {
//   getRouteString,
//   getCurrencyList,
//   getPermissionList
// } from '@/utils/auth'
// import { _import } from '@/control'
// import Layout from '@/layout'
import router from '@/router'
import { getValue, saveValue } from '../../utils/auth'
// import store from '../index'

// router.push({ path: '/' })

const getDefaultState = () => {
  return {
    name: '',
    headUrl: '',
    activeMen: '',
    isPC: true,
    companyInfo: {},
    route: constantRoutes,
    role: 0,
    userId: 0,
    categoryList: [],
    shopCart: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_ROLE: (state) => {
    state.role = parseInt(getroleID())
  }, // role
  SET_ACTIVEMENU: (state, activeMen) => {
    state.activeMen = activeMen
  }, // role
  SET_ISPC: (state) => {
    state.isPC = !(isPhone())
  }, // role
  SET_USERINFO: (state) => {
    const userInfo = localStorage.getItem('userInfo') ? getValue('userInfo') : null
    if (userInfo) {
      state.name = userInfo.name
      state.headUrl = userInfo.headUrl
    }
    infoUserApi().then(res => {
      saveValue('userInfo', res.data)
      state.name = res.data.name
      state.headUrl = res.data.headUrl
    }).catch(err => {
      console.log(err)
      state.name = 'User'
      state.headUrl = ''
    })
  }, // name
  SET_NAME: (state, name) => {
    state.name = name
  }, // role
  SET_HEADURL: (state, headUrl) => {
    state.headUrl = headUrl
  }, // role
  SET_SHOPCART(state) {
    const token = hasTokens()
    if (token) {
      order_querycartApi().then(res => {
        state.shopCart = res.data
        state.shopCart.total = 0
        if (res.data) {
          if (res.data.length) {
            if (res.data.length > 0) {
              state.shopCart = res.data
              for (let i = 0; i < res.data.length; i++) {
                state.shopCart.total = state.shopCart.total + res.data[i].total
              }
            }
          }
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }, // 购物车
  SET_CATEGORYLIST: (state) => {
    state.categoryList = getCategoryTypeList()
  }, // 商品种类List
  SET_ADDROUTES: (state) => {
    const hasToken = getToken()
    const isPC = !(isPhone())
    const role = parseInt(getroleID())
    let permission = superAdminRoutes
    if (!hasToken) {
      Promise.reject(false)
    }
    switch (role) {
      case adminV:
        if (isPC) {
          permission = superAdminRoutes
        } else {
          permission = MsuperAdminRoutes
        }
        break
      case agencyV:
        if (isPC) {
          permission = bigAgentRoutes
        } else {
          permission = MbigAgentRoutes
        }
        break
      case dealerMV:
        if (isPC) {
          permission = mainDealerRoutes
        } else {
          permission = MmainDealerRoutes
        }
        break
      case dealerV:
        if (isPC) {
          permission = smallDealerRoutes
        } else {
          permission = MsmallDealerRoutes
        }
        break
      default:
        removeroleID()
        break
    }
    router.addRoutes(permission)
    router.options.routes.push(...permission)
  }, // 添加动态路由
  SET_RESETROUTE(state) {
    router.options.routes = []
    state.route = constantRoutes
    resetRouter()
  } // 重置路由
}

const actions = {
  login({ commit }, userInfo) {
    const { acc, pwd } = userInfo
    return new Promise((resolve, reject) => {
      loginUserApi({ acc: acc, pwd: pwd }).then(response => {
        if (response.data.token && response.data.dealerId) {
          saveUserName(acc)
          saveToken(response.data.token)
          saveroleID(response.data.roleType)
          commit('SET_ADDROUTES')
          resolve(response.data.roleType)
        } else {
          Promise.reject(false)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      removeAllSavedValue()
      commit('SET_RESETROUTE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
